package main

import (
	"errors"
	"math"
)

// 计算均值
func mean(data []float64) float64 {
	sum := 0.0
	for _, v := range data {
		sum += v
	}
	return sum / float64(len(data))
}
func PearsonCorrelation(x, y []float64) (float64, error) {
	// 检查数组长度是否一致
	if len(x) != len(y) {
		return 0, errors.New("arrays must have the same length")
	}
	n := len(x)
	if n == 0 {
		return 0, errors.New("arrays cannot be empty")
	}

	// 计算均值
	meanX := mean(x)
	meanY := mean(y)

	// 计算协方差和标准差
	var covariance, sumX, sumY float64
	for i := 0; i < n; i++ {
		devX := x[i] - meanX
		devY := y[i] - meanY
		covariance += devX * devY
		sumX += devX * devX
		sumY += devY * devY
	}

	// 计算标准差
	stdDevX := math.Sqrt(sumX / float64(n))
	stdDevY := math.Sqrt(sumY / float64(n))

	// 避免除以零
	if stdDevX == 0 || stdDevY == 0 {
		return 0, errors.New("standard deviation of one array is zero")
	}

	// 计算相关系数
	correlation := covariance / float64(n) / (stdDevX * stdDevY)
	return correlation, nil
}
